using System;
using System.Collections.Generic;
using System.Text;
using RideMe.Core;
using System.Web;
using System.Diagnostics;

namespace RideMe.Presentation.ExceptionManagement
{
    public class ExceptionPublisher
    {

        /// <summary>
        /// Shows the exception dialog.
        /// </summary>
        /// <param name="excp">The exception.</param>
        public static void ShowExceptionDialog(Exception excp)
        {
            using (ExceptionDialog dialog = new ExceptionDialog())
            {
                dialog.Exception = excp;
                dialog.ShowDialog();
            }
        }

        /// <summary>
        /// Publishes the exception.
        /// </summary>
        /// <param name="excp">The exception.</param>
        /// <returns></returns>
        public static bool PublishException(Exception excp)
        {
            bool published = false;

            LogService loggingService = null;

            try
            {
                loggingService = new LogService();
                published = loggingService.LogException(DateTime.Now, excp);
            }
            catch (System.Web.Services.Protocols.SoapException e)
            {
#if DEBUG
                using (DebugExceptionDialog dialog = new DebugExceptionDialog(e))
                {
                    dialog.ShowDialog();
                }
#endif
            }
            catch { }
            finally
            {
                loggingService.Dispose();
            }

            return published;
        }

        /// <summary>
        /// Sends the bug.
        /// </summary>
        /// <param name="excp">The exception.</param>
        /// <returns></returns>
        public static bool SendBug(Exception excp)
        {
            string tracAddress = RideMe.Presentation.Properties.Resources.TracAddress;

            string exceptionToString = "{{{\n" + excp.ToString() + "\n}}}";
            tracAddress += "description=" + HttpUtility.UrlEncode(exceptionToString);

            Process command = new Process();

            try
            {
                command.StartInfo.FileName = tracAddress;
                command.StartInfo.UseShellExecute = true;
                command.Start();
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                command.Close();
            }

            return true;
        }
    }
}
